文章目录
  1. 1. 参考
  2. 2. 自己的代码
  3. 3. 解决方案如下

都觉得springboot集成rabbitmq非常简单,springboot都提供了现成的stater出来了,不就是引入依赖包后,就几行代码就搞定的事情吗?

参考

官方例子

自己的代码

  • 生产者
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Product 
{

@Autowired
private RabbitTemplate rabbitTemplate;

@Scheduled(fixedDelay = 100L)
public void product() {
User user = new User();
user.setId(24545);
user.serName("lvk");
user.setAdress("GDGZTH");
this.rabbitTemplate.convertAndSend("queueName", user);
}
}
  • 消费者
1
2
3
4
5
6
7
8
9
10
11
@Service
@RabbitListener(queues = "queueName")
public class Consumer {
protected Logger logger = Logger.getLogger(Consumer.class);

@RabbitHandler
public void process(@Payload User user) {
UserResponse response = new UserResponse();
logger.info(user.getId() + "->" + response.getRetCode());
}
}

看控制台日志输出:

1
2
3
org.springframework.amqp.AmqpException: No method found for class 

死循环似的输出......

解决方案如下

在初始化的时候先构建如下两个bean:

  • RabbitTemplate
1
2
3
4
5
6
7
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory)
{
RabbitTemplate template = new RabbitTemplate(connectionFactory);
template.setMessageConverter(new Jackson2JsonMessageConverter());
return template;
}
  • SimpleRabbitListenerContainerFactory (消息监听器工厂)
1
2
3
4
5
6
7
8
@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory)
{
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setMessageConverter(new Jackson2JsonMessageConverter());
return factory;
}

然后将以上消费者的代码修改为如下:

1
2
3
4
5
6
7
8
9
10
11
12
@Service
public class Consumer
{
protected Logger logger = Logger.getLogger(Consumer.class);

@RabbitListener(queues = "queueName", containerFactory="rabbitListenerContainerFactory")
public void process(@Payload User user)
{
UserResponse response = new UserResponse();
logger.info(request.getId() + "->" + response.getRetCode());
}
}

继续看控制台日志,没有报错,并输出正确的日志,问题解决!

文章目录
  1. 1. 参考
  2. 2. 自己的代码
  3. 3. 解决方案如下